#include "unp.h"

static void str_echo(int sockfd){
	char buf[MAXLINE];
	int n;
	while( (n = read(sockfd, buf, sizeof(buf))) > 0){
		write(sockfd, buf, n);
	}
	if(n < 0)
		err_sys("read error");
}
int main(){
	int		listenfd, connfd;
	pid_t	childpid;
	socklen_t	cli_len;
	struct sockaddr_in	cliaddr, servaddr;

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(SERV_PORT);
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

	Bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));

	Listen(listenfd, 100);
	while(1){
		connfd = Accept(listenfd, (struct sockaddr*)&cliaddr, &cli_len);
		
		if( (childpid = Fork()) == 0){			/* after fork, all the file descriptors are duplicated */
			Close(listenfd);
			str_echo(connfd);
			exit(0);
		}
		Close(connfd);
	}

}
